package com.brother.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.alibaba.fastjson.JSON;

public class JSONView extends AbstractView {

	private boolean disableCaching = true;
	private String encoding = "utf-8";
	
	public JSONView(){
		setContentType("application/json");
	}
	
	
	
	public boolean isDisableCaching() {
		return disableCaching;
	}

	public void setDisableCaching(boolean disableCaching) {
		this.disableCaching = disableCaching;
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		System.out.println("model="+JSON.toJSONString(model));
		ServletOutputStream out = res.getOutputStream();
		if(model.isEmpty()){
			out.write("".getBytes());
		}else{
			out.write(JSON.toJSONString(model).getBytes());
		}
	}

	@Override
	public void render(Map<String, ?> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		super.render(model, request, response);
	}

	@Override
	protected void writeToResponse(HttpServletResponse response,
			ByteArrayOutputStream baos) throws IOException {
		super.writeToResponse(response, baos);
	}

	@Override
	protected void prepareResponse(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType(getContentType());
		response.setCharacterEncoding(this.encoding);
		if (this.disableCaching) {
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
			response.addDateHeader("Expires", 1L);
		}
	}

	
	
}
